package com.example.day11;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Telephony;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    public static TextView mText;
    Button Button;
    ImageView imageShow;
    GridView grid;
    Myadapter myAdapter;
    ArrayList<String> list =new ArrayList<>();
    private SmsContent content;
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkAccess(new String[]{Manifest.permission.READ_SMS},1);
        grid=findViewById(R.id.grid1);
        mText = (TextView) findViewById(R.id.text);
        imageShow=findViewById(R.id.imageShow);
        Button=(Button)findViewById(R.id.button1);
        Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                map();
            }
        });
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                imageShow.setVisibility(View.VISIBLE);
                Glide.with(MainActivity.this).load(list.get(position)).into(imageShow);
            }
        });
        imageShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageShow.setVisibility(View.GONE);
            }
        });
        //注册短信变化监听
        content = new SmsContent(new Handler(),this);
        this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"),
                true, content);

    }

    private void checkAccess(String[] access,int code){
        //Manifest.permission.READ_EXTERNAL_STORAGE
        //检查当前权限（若没有该权限，值为-1；若有该权限，值为0）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasAccess = ContextCompat.checkSelfPermission(getApplication(),access[0]);
            Log.e("PERMISION_CODE", hasAccess + "***");
            if (hasAccess == PackageManager.PERMISSION_GRANTED) {
                // TODO: 2019/6/15 获得授权执行操作
//                if(code==1){
//                    readUser();
//                }else if(code==2){
//                    readSMS();
//                }

            } else {
                ActivityCompat.requestPermissions(this, access, code);
            }
        }else{
            // TODO: 2019/6/15 非6.0直接使用
//            if(code==1){
//                readUser();
//            }else if(code==2){
//                readSMS();
//            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        this.getContentResolver().unregisterContentObserver(content);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (permissions[0].equals(Manifest.permission.READ_CONTACTS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // TODO: 2019/6/15 获得授权执行操作
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1
        } else {
            // TODO: 2019/6/15 未获得授权执行的操作
//            finish();
        }
    }


    private void call() {
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得图库的URI
        Uri uri1 = CallLog.Calls.CONTENT_URI;//图库的URI
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        while (cursor.moveToNext()){
            //字段
            String title=cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
            String data=cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE));
            String artist=cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
            long duration=cursor.getLong(cursor.getColumnIndex(CallLog.Calls.TYPE));
            Log.d("###", "通话记录: "+title+":"+data+":"+artist+":"+duration+":");
        }
    }
    /**
     * 	4.获取联系人：
     * 	(1)uri:ContactsContract.CommonDataKinds.Phone.CONTENT_URI
     * 	(2)字段：
     * 	    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME：姓名
     * 	    ContactsContract.CommonDataKinds.Phone.NUMBER：电话
     * */
    private void person() {
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得图库的URI
        Uri uri1 = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;//图库的URI
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        while (cursor.moveToNext()){
            //字段
            String title=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String data=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d("###", "联系人: "+title+":"+data+":");
        }
    }
    /**
     * 5.通话记录
     * (1)uri:Telephony.Sms.CONTENT_URI
     * (2)字段：ADDRESS 地址   BODY 内容
     * */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void message() {
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得图库的URI
        Uri uri1 = Telephony.Sms.CONTENT_URI;
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        while (cursor.moveToNext()){
            //字段
            String address=cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            String body=cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            String creator=cursor.getString(cursor.getColumnIndex(Telephony.Sms.CREATOR));
            String date=cursor.getString(cursor.getColumnIndex(Telephony.Sms.DATE));
            Log.d("###", "短信: "+address+":"+body+":"+creator+":"+date);
        }
    }
    /**
     * 获取图库：
     * (1)uri:MediaStore.Images.Media.EXTERNAL_CONTENT_URI
     * (2)字段：
     *  				MediaStore.Images.Media.TITLE;图片名称
     * 					MediaStore.Images.Media.SIZE;大小
     * 					MediaStore.Images.Media.DATA;地址
     * >
     *
     *
     * */
    public void map(){
        Toast.makeText(this, "2222", Toast.LENGTH_SHORT).show();
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得图库的URI
        Uri uri1 = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;//图库的URI
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        int aa=0;
        list=new ArrayList<>();
        while (cursor.moveToNext()){
//            Toast.makeText(this, "1111", Toast.LENGTH_SHORT).show();
            Log.e("###",""+aa++);
            //字段
            String title=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.TITLE));
            String data=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            int height=cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.HEIGHT));
            int width=cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media.WIDTH));
            long size=cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.SIZE));
            Log.e("###", "图片: "+title+":"+data+":"+height+":"+width+":"+size);
            list.add(data);
        }

        myAdapter=new Myadapter(MainActivity.this,list);
        grid.setAdapter(myAdapter);
    }
    /**
     * 2.获取视频：
     * (1)uri:MediaStore.Video.Media.EXTERNAL_CONTENT_URI
     * (2)字段：TITLE：歌名   ARTIST 歌手   DURATION 总时长  DATA 地址
     * String[] strs= new String[]{MediaStore.Video.Media.TITLE,MediaStore.Video.Media.ARTIST,MediaStore.Video.Media.DURATION,MediaStore.Video.Media.DATA};

     * */
    public void video(){
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null
        //TODO 2:获得图库的URI

        Uri uri1 = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;//图库的URI
//        Uri uri1 = Uri.parse("content://media/external/video/media");
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        while (cursor.moveToNext()){
            //字段
            String title=cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
            String data=cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
            String artist=cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.ARTIST));
            long duration=cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
            long size=cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));
            Log.e("###", "视频: "+title+":"+data+":"+artist+":"+duration+":"+size);
        }
    }
    public void music(){
        //TODO 1:获得ContentResolver
        ContentResolver contentResolver = getContentResolver();
        //参数一 URI   null

        Uri uri1 = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//
        Cursor cursor = contentResolver.query(uri1, null, null, null, null);
        while (cursor.moveToNext()){
            //字段
            String title=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String data=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            String artist=cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            long duration=cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            long size=cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));
            Log.d("###", "音乐: "+title+":"+data+":"+artist+":"+duration+":"+size);
        }
    }

}

